/* global window */
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { info as clientInfo, list as clientList } from 'services/client'
import { info as orgInfo, getPartyUserList, getAllORGList, list as orgList } from 'services/org'
import { tagListService, memoTagList, list as queryBasicInfoList, addDefaultItemsService } from 'services/basicInfo'
import { list, info, allList, addAndEdit, getMatterDetailsListService, getWordInfoService, saveWordService, downloadWordService } from 'services/acceptance'
import {
  priceGroupSave,
  priceGroupRemove,
  chargeInterfaceList,
  chargeInterfaceSave,
  chargeInterfaceUpdate,
  chargeInterfaceRemove,
  priceSettingEnable,
  priceSettingDisable,
  priceSettingUpdate
} from 'services/price'

import { pageModel } from 'utils/model'

const { prefix } = config

export default modelExtend(pageModel, {
  namespace: 'acceptance',

  state: {
    currentItem: {},
    currentDetailInfo: {},
    showModalDefault: false,
    visibleDetails: false,
    currentInfo: {
      basicInfo: {},
      fileList: [],
      partyList: []
    },
    visibleDetailsModal: false,
    keywords: '',
    detailsInfo: {},
    modalVisible: false,
    modalType: 'create',
    // modalTypes:'create',
    selectedRowKeys: [],
    treeCheckedKeys: [],
    isMotion: window.localStorage.getItem(`${prefix}userIsMotion`) === 'true',
    priceGroupList: [],
    modelVisibleGroup: false,
    interfaceList: [],
    visibleCreateApi: false,
    currentApiItem: {},
    currentMethod: '',
    showClientAndMattersNameVisible: false,
    showClient: true,
    clientList: [],
    infoChecked: '',
    selectedRowKeysClient: [],
    // AllClientList: [],
    orgListData: [],
    showFinalMatter: false,
    // AllORGList: [],
    ExamineModalVisible: false,
    selectedRowKeysORG: [],
    clientRowKeys: [],
    showAddView: false,
    PartyClientKeys: [],
    PartyClientList: [],
    PartyORGKeys: [],
    PartyORGList: [],
    partyList: [],
    PartyClientKeysCancle: [],
    PartyORGKeysCancle: [],
    name: ["合同", "买卖合同", "房屋买卖合同"],
    translation: '',
    currency: '',
    number: '',
    matterIndex: 1,
    matter: [],
    matterOtherData: {},
    vedioList: [],
    urrentDetailedIMG: [],
    showTheCurrentDetailedIMG: false,
    examineData: {},
    showCascader: false,
    matterId: '',
    fileList: {},
    isEditMatter: false,
    memoList: [],
    isEditBatch: false,
    infoId: '',
    supplementState: { "1": false, "2": false, "3": false, "4": false, "5": false },
    showEditWords: false,
    personIndex: 1,
    getWordInfo: {},
    showEditForeign: false,
    getForeignInfo: {},
    showEditCompany: false,
    getCompanyInfo: {},
    agentIndex: 1,
    tagList: [],
    tagNameArry: [],
    tagModalType: 'create',
    basicInfoList: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/app/acceptance') {
          dispatch({
            type: 'query',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {
    *addDefaultItems({ payload, }, { call, put }) {
      const addDefaultItemsData = yield call(addDefaultItemsService, payload)
      const data = yield call(queryBasicInfoList, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            basicInfoList: data.list,
            showModalDefault: false,
          },
        })
      } else {
        throw data
      }
    },
    *examine({ payload, }, { call, put }) {
      const data = yield call(tagListService, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            examineData: payload.examineData,
            ExamineModalVisible: true,
          },
        })
      } else {
        throw data
      }
    },
    * queryTagLsit({ payload, }, { call, put }) {
      const data = yield call(tagListService, payload)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            tagList: data.list,
            showModalDefault: true,
            tagModalType: 'create',
          },
        })
      } else {
        throw data
      }
    },
    *choiceMatter({ payload = {} }, { call, put }) {
      const data = yield call(queryBasicInfoList, payload)
      if (data) {
        yield put({
          type: 'currentMethod',
          payload: {
            basicInfoList: data.list,
            showClient: false,
          },
        })
      }
    },
    * query({ payload = {} }, { call, put }) {
      const data = yield call(allList, payload)
      const clientListData = yield call(clientList, payload)
      sessionStorage.removeItem('organizationId')
      if (data) {
        yield put({
          type: 'currentMethod',
          payload: {
            list: data.page.list,
            clientList: clientListData.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount
            },
          },
        })
      }
    },
    * changePage({ payload }, { call, put }) {
      const data = yield call(allList, { page: payload.page, pageSize: payload.pageSize, keywords: payload.keywords })
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount
            },
          },
        })
      }
    },

    *editWord({ payload }, { call, put }) {
      const data = yield call(getWordInfoService, { type: 0, matterId: payload.matterId });
      yield put({
        type: 'currentMethod',
        payload: {
          showEditWords: true,
          getWordInfo: data.data,
          personIndex: (JSON.parse(data.data.userInfo)).length
        },
      })
    },
    *editForeign({ payload }, { call, put }) {
      const data = yield call(getWordInfoService, { type: 2, matterId: payload.matterId });
      yield put({
        type: 'currentMethod',
        payload: {
          showEditForeign: true,
          getForeignInfo: data.data,
          personIndex: (JSON.parse(data.data.userInfo)).length
        },
      })
    },
    * queryKeyWords({ payload }, { call, put }) {
      const data = yield call(allList, { ...payload })
      if (data) {
        yield put({
          type: 'currentMethod',
          payload: {
            keywords: payload.keywords,
            list: data.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount
            },
          },
        })
      }
    },
    *editCompany({ payload }, { call, put }) {
      const data = yield call(getWordInfoService, { type: 1, matterId: payload.matterId });
      yield put({
        type: 'currentMethod',
        payload: {
          showEditCompany: true,
          getCompanyInfo: data.data,
          personIndex: (JSON.parse(data.data.userInfo)).length
        },
      })
    },
    *downPeopleModels({ payload }, { call, put }) {
      const data = yield call(downloadWordService, { type: 0, matterId: payload.matterId });
    },
    *saveWordTable({ payload }, { call, put }) {
      const data = yield call(saveWordService, { type: payload.type, matterId: payload.matterId, data: payload.data });
      yield put({
        type: 'currentMethod',
        payload: {
          showEditWords: false,
          showEditForeign: false,
          showEditCompany: false,
          getWordInfo: {},
          getCompanyInfo: {},
          getWordInfo: {}
        },
      })
    },
    * onChangeClients({ payload }, { call, put }) {
      const data = yield call(clientList, { ...payload });
      if (data) {
        for (let index = 0; index < data.page.list.length; index++) {
          data.page.list[index].key = data.page.list[index].id
        }
        yield put({
          type: 'priceGroupListSuccess',
          payload: {
            clientList: data.page.list,
            paginationClientList: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount
            },
          },
        })
      }
    },
    * addAndEditBatch({ payload }, { call, put }) {
      const data = yield call(addAndEdit, { ...payload });
      if (data) {
        const datas = yield call(allList, payload)
        if (datas) {
          yield put({
            type: 'currentMethod',
            payload: {
              list: datas.page.list,
              pagination: {
                current: Number(payload.page) || 1,
                pageSize: Number(payload.pageSize) || 10,
                total: datas.page.totalCount
              },
            },
          })
          window.location.reload(true)
        }
      }
    },
    * addNewBatch({ payload = {} }, { call, put }) {
      const clientListData = yield call(clientList, payload)
      const orgListData = yield call(orgList, payload)
      // const AllClientList = yield call(getPartyUserList, payload)
      // const AllORGList = yield call(getAllORGList, payload)
      if (orgListData) {
        if (clientListData) {
          for (let index = 0; index < clientListData.page.list.length; index++) {
            clientListData.page.list[index].key = clientListData.page.list[index].id
          }
          yield put({
            type: 'priceGroupListSuccess',
            payload: {
              // AllORGList: AllORGList.list,
              orgListData: orgListData.page.list,
              // AllClientList: AllClientList.list,
              clientList: clientListData.page.list,
              paginationClientList: {
                current: Number(payload.page) || 1,
                pageSize: Number(payload.pageSize) || 10,
                total: clientListData.page.totalCount
              },
              paginationMatter: {
                current: Number(payload.page) || 1,
                pageSize: Number(payload.pageSize) || 10,
                total: orgListData.page.totalCount
              },
              partyList: [],
              PartyORGList: [],
              PartyClientList: [],
              PartyORGKeys: [],
              PartyClientKeys: [],
              PartyClientKeysCancle: [],
              PartyORGKeysCancle: [],
              selectedRowKeysClient: [],
              clientRowKeys: [],
              selectedRowKeysORG: [],
              ORGRows: [],
              matter: [],
              matterOtherData: {},
              showFinalMatter: false,
              vedioList: [],
              showClient: true,
              showClientAndMattersNameVisible: true,
              fileList: {},
              matterOtherData: []
            },
          })
        } else {
          throw clientListData
        }
      }
      else {
        throw orgListData
      }
    },
    * onChangeMatters({ payload }, { call, put }) {
      const data = yield call(orgList, { ...payload });
      if (data) {
        for (let index = 0; index < data.page.list.length; index++) {
          data.page.list[index].key = data.page.list[index].id
        }
        yield put({
          type: 'priceGroupListSuccess',
          payload: {
            orgListData: data.page.list,
            paginationMatter: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount
            },
          },
        })
      }
    },
    * info({ payload }, { call, put }) {
      const data = yield call(info, { id: payload.currentItem.id });
      if (data.success) {
        yield put({
          type: 'showDetails',
          payload: {
            currentItem: payload.currentItem,
            visibleDetails: payload.visibleDetails,
            currentInfo: {
              basicInfo: data.basicInfo,
              fileList: data.fileList,
              partyList: data.partyList
            }
          }
        })
      } else {
        throw data
      }
    },
    * EditData({ payload }, { call, put }) {
      // console.log(payload.currentItem, 'payload.currentItem') //selectedRowKeysClient  selectedRowKeysORG
      const clientListData = yield call(clientList, {})
      const orgListData = yield call(orgList, {})
      if (clientListData) {
        for (let index = 0; index < clientListData.page.list.length; index++) {
          clientListData.page.list[index].key = clientListData.page.list[index].id
        }
        yield put({
          type: 'priceGroupListSuccess',
          payload: {
            clientList: clientListData.page.list,
            paginationClientList: {
              current: 1,
              pageSize: 10,
              total: clientListData.page.totalCount
            },
          },
        })
      }
      if (orgListData) {
        yield put({
          type: 'priceGroupListSuccess',
          payload: {
            orgListData: orgListData.page.list,
            paginationMatter: {
              current: 1,
              pageSize: 10,
              total: orgListData.page.totalCount
            },
          },
        })
      }
      const data = yield call(getMatterDetailsListService, { id: payload.currentItem.batchNumber });
      let matterList = payload.currentItem.mattersList
      console.log(data, 'data')
      let matterArry = [];
      let partyNameArry = []
      if (matterList.length != 0) {
        matterList.map((item) => {
          partyNameArry.push(item.partyStr)
        })
      }
      data.info.map((item, index) => {
        matterArry.push(
          {
            supplementState: item.matterInfo.supplementData != undefined && item.matterInfo.supplementData != null ? JSON.parse(item.matterInfo.supplementData) : item.matterInfo.supplementData,
            id: parseInt(item.matterInfo.notarizationMatters),
            video: item.matterInfo.video,
            number: item.matterInfo.number != undefined && item.matterInfo.number != null ? parseInt(item.matterInfo.number) : item.matterInfo.number,
            idCard: JSON.parse(item.matterInfo.partyData).idCard,
            creditCode: JSON.parse(item.matterInfo.partyData).creditCode,
            name: item.matterInfo.mattersName,
            memo: item.matterInfo.remark,
            tags: item.matterInfo.tags,
            translation: item.matterInfo.translation,
            currency: item.matterInfo.currency,
            index: index + 1,
            infoId: parseInt(item.matterInfo.basicinfoId) || 0,
            partyName: partyNameArry[index],
            files: item.files || {},
          }
        )
      })
      let clientRowKeys = []
      let ORGRows = []
      let selectedRowKeysClient = []
      let selectedRowKeysORG = []
      if (payload.currentItem.partyUsers != null && payload.currentItem.partyUsers.length > 0 && payload.currentItem.partyUsers != undefined) {
        clientRowKeys = payload.currentItem.partyUsers.map((item) => {
          return item.card
        })
      }
      if (payload.currentItem.partyOrgs != null && payload.currentItem.partyOrgs.length > 0 && payload.currentItem.partyOrgs != undefined) {
        ORGRows = payload.currentItem.partyOrgs.map((item) => {
          return item.card
        })
      }
      if (payload.currentItem.partyUsers != null && payload.currentItem.partyUsers.length > 0 && payload.currentItem.partyUsers != undefined) {
        selectedRowKeysClient = payload.currentItem.partyUsers.map((item) => {
          return { idCard: item.card, name: item.name }
        })
      }
      if (payload.currentItem.partyOrgs != null && payload.currentItem.partyOrgs.length > 0 && payload.currentItem.partyOrgs != undefined) {
        selectedRowKeysORG = payload.currentItem.partyOrgs.map((item) => {
          return { creditCode: item.card, name: item.name }
        })
      }
      let matterOtherData = {}
      let payInfoList = payload.currentItem.payInfoList || []
      console.log(payInfoList, 'payInfoList')
      if (payInfoList.length != 0) {
        payInfoList.map((item) => {
          if (!matterOtherData[item.localId]) {
            matterOtherData[item.localId] = {}
          }
          matterOtherData[item.localId]["cost"] = item.money
        })
      }
      matterOtherData["feeChecked"] = parseInt(payload.currentItem.payState) || 0
      matterOtherData["approvalLevel"] = payload.currentItem.approvalLevel + ''
      sessionStorage.setItem("batchId", payload.currentItem.localId)
      yield put({
        type: 'currentMethod',
        payload: {
          showClientAndMattersNameVisible: true,
          matterOtherData: matterOtherData,
          clientRowKeys: clientRowKeys,
          ORGRows: ORGRows,
          selectedRowKeysClient: selectedRowKeysClient,
          selectedRowKeysORG: selectedRowKeysORG,
          isEditBatch: true,
          matter: matterArry,
          infoId: matterArry.length != 0 ? parseInt(matterArry[0].infoId) : 0,
        }
      })
    },
    // 回显编辑事项
    * editMatterModels({ payload }, { call, put }) {
      console.log(payload, 'payload')
      // editIndex
      let partyList = []
      let peopleList = payload.row.idCard.split(',')
      let orgLists = payload.row.creditCode.split(',')
      const filterClient = (arr1, arr2) => {
        return arr1.filter((ele) =>
          arr2.filter((x) => x === ele.idCard).length > 0
        );
      }
      const filterORG = (arr1, arr2) => {
        return arr1.filter((ele) =>
          arr2.filter((x) => x === ele.creditCode).length > 0
        );
      }
      let currentPeople = filterClient(payload.selectedRowKeysClient, peopleList)
      currentPeople.map((item) => {
        partyList.push({ name: item.name, id: item.idCard, partyType: '0' })
      })
      let currentORG = filterORG(payload.selectedRowKeysORG, orgLists)
      currentORG.map((item) => {
        partyList.push({ name: item.name, id: item.creditCode, partyType: '1' })
      })

      // let name = payload.name
      let matterOtherData = payload.matterOtherData
      const matterId = sessionStorage.getItem("matterId")
      if (!matterOtherData[matterId]) {
        matterOtherData[matterId] = {}
      }
      matterOtherData[matterId]["memoText"] = payload.row.memo
      const dataTag = yield call(tagListService, {});
      const memoListData = yield call(memoTagList, {});
      let currentArry = payload.row.video.split('#')
      currentArry.pop()
      yield put({
        type: 'currentMethod',
        payload: {
          name: payload.row.name,
          getTagList: dataTag.list,
          memoList: memoListData.list,
          showFinalMatter: true,
          number: payload.row.number,
          partyList: partyList,
          fileList: payload.row.files,
          isEditMatter: true,
          matterOtherData: matterOtherData,
          memoText: payload.row.memo,
          infoId: payload.row.infoId || 0,
          translation: payload.row.translation,
          currency: payload.row.currency,
          // supplementState: payload.row.supplementState
          supplementState: typeof (payload.row.supplementState) == 'string' ? JSON.parse(payload.row.supplementState) : payload.row.supplementState,
          vedioList: currentArry
        }
      })
    },
    * showPriceGroup({ payload }, { call, put }) {
      yield put({
        type: 'showModal',
        payload: {
          modalType: payload.modalType,
          modelVisibleGroup: true
        },
      })
    },
    * createPriceGroup({ payload }, { call, put }) {
      const data = yield call(priceGroupSave, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * removePriceGroup({ payload }, { call, put }) {
      const data = yield call(priceGroupRemove, { priceGroupId: payload.priceGroupId })
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * interfaceList({ payload }, { call, put }) {
      const data = yield call(chargeInterfaceList)
      if (data.success) {
        yield put({
          type: 'showModal',
          payload: {
            interfaceList: data.interfaceList,
            modalType: payload.modalType
          },
        })
      } else {
        throw data
      }
    },

    * interfaceListNew({ payload }, { call, put }) {
      const data = yield call(chargeInterfaceList)
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            interfaceList: data.interfaceList
          },
        })
      } else {
        throw data
      }
    },

    //禁用
    * settingDisable({ payload }, { call, put }) {
      const data = yield call(priceSettingDisable, payload)
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    //启用
    * settingEnable({ payload }, { call, put }) {
      const data = yield call(priceSettingEnable, payload)
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * create({ payload }, { call, put }) {
      const data = yield call(chargeInterfaceSave, payload)
      if (data.success) {
        yield put({ type: 'interfaceListNew' })
        yield put({ type: 'hideCreateApi' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * deleteInterface({ payload }, { call, put }) {
      const data = yield call(chargeInterfaceRemove, { interfaceIds: payload })
      if (data.success) {
        yield put({ type: 'interfaceListNew' })
        yield put({ type: 'hideCreateApi' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * showUpdateApi({ payload }, { call, put }) {
      yield put({
        type: 'showCreateApi',
        payload: {
          currentItem: payload.currentItem ? payload.currentItem : {},
          currentApiItem: payload.currentApiItem ? payload.currentApiItem : {},
          modalType: payload.modalType
        }
      })
    },

    * updateInterface({ payload }, { call, put }) {
      const data = yield call(chargeInterfaceUpdate, payload.data)
      if (data.success) {
        yield put({ type: 'interfaceListNew' })
        yield put({
          type: 'hideCreateApi',
          payload: {
            modalType: payload.modalType
          }
        })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * update({ payload }, { call, put }) {
      const data = yield call(priceSettingUpdate, payload)
      if (data.success) {
        yield put({ type: 'query' })
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    * clientInfo({ payload }, { call, put }) {
      if (payload.partyType === 1) {
        const data = yield call(orgInfo, { id: payload.card });
        if (data.success) {
          yield put({
            type: 'showDetailsModal',
            payload: {
              // currentItem: payload,
              currentDetailInfo: {
                appPartyUser: data.appPartyOrganization,
                partyFile: data.partyFile,
                type: "org"
              }
            }
          })
        } else {
          throw data
        }
        return
      }
      const data = yield call(clientInfo, { id: payload.card });
      if (data.success) {
        yield put({
          type: 'showDetailsModal',
          payload: {
            // currentItem: payload,
            currentDetailInfo: {
              appPartyUser: data.appPartyUser,
              comparisonRecordList: data.comparisonRecordList,
              partyFile: data.partyFile,
              type: "client"
            }
          }
        })
      } else {
        throw data
      }
    },
    // showFinalMatter
    * showNewMatterViewVisible({ payload }, { call, put }) {
      const dataTag = yield call(tagListService, payload = {});
      const memoListData = yield call(memoTagList, payload = {});
      let matterOtherData = {}
      const matterId = sessionStorage.getItem("matterId")
      if (!matterOtherData[matterId]) {
        matterOtherData[matterId] = {}
      }
      matterOtherData[matterId]["memoText"] = ''
      // showNewMatterViewVisibleReducers
      yield put({
        type: 'showNewMatterViewVisibleReducers',
        payload: {
          name: ["合同", "买卖合同", "房屋买卖合同"],
          getTagList: dataTag.list,
          memoList: memoListData.list,
          showFinalMatter: true,
          number: 0,
          partyList: [],
          fileList: {},
          isEditMatter: false,
          matterOtherData: matterOtherData,
          memoText: '',
          infoId: '',
          translation: '',
          currency: '',
          supplementState: { "1": false, "2": false, "3": false, "4": false, "5": false },
          vedioList: []
        }
      })
    },
  },

  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },
    hideshowClientAndMattersNameVisible(state, { payload }) {
      return { ...state, ...payload, showClientAndMattersNameVisible: false }
    },
    showNewMatterViewVisibleReducers(state, { payload }) {
      return { ...state, ...payload, showFinalMatter: true }
    },
    goToclientAndMatterViewVisible(state, { payload }) {
      return { ...state, ...payload, showFinalMatter: false }
    },
    choiceClientReducers(state, { payload }) {
      return { ...state, ...payload, showClient: true }
    },
    choiceMatterReducers(state, { payload }) {
      return { ...state, ...payload, showClient: false }
    },
    showClientAndMattersName(state, { payload }) {
      return { ...state, ...payload, showClientAndMattersNameVisible: true, }
    },
    hideModal(state) {
      return { ...state, modalVisible: false, modelVisibleGroup: false, visibleCreateApi: false }
    },

    switchIsMotion(state) {
      window.localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
      return { ...state, isMotion: !state.isMotion }
    },

    priceGroupListSuccess(state, { payload }) {
      return { ...state, ...payload }
    },

    showCreateApi(state, { payload }) {
      return { ...state, ...payload, modalVisible: true, visibleCreateApi: true }
    },
    hideCreateApi(state, { payload }) {
      return { ...state, ...payload, modalVisible: true, visibleCreateApi: false }
    },

    currentMethod(state, { payload }) {
      return { ...state, ...payload }
    },

    //acceptance method
    showDetails(state, { payload }) {
      return { ...state, ...payload }
    },
    hideDetails(state, { payload }) {
      return { ...state, ...payload }
    },
    showDetailsModal(state, { payload }) {
      return { ...state, ...payload, visibleDetailsModal: true, detailsInfo: { ...payload } }
    },
    hideDetailsModal(state, { payload }) {
      return { ...state, ...payload, visibleDetailsModal: false }
    },
  },
})
